import api from './api'
import base from 'think-react-app/lib/base'

import React from 'react';
import Store from '../../../view/store';
import ContextProvider from '../../../view/components/ContextProvider';
import providesStore from '../../../view/store/providesStore';

export default class extends base(api) {
	async __before() {
		await super.__before();

		// const signInfo = await this.session('signInfo');

		// if (!signInfo) {
		// 	const appCode = this.params('appcode');
		// 	const appInfo = this.config('appinfo')[appCode];
		// 	const userInfo = await this.service(appCode)(appInfo);

		// 	await this.session('signInfo', {
		// 		appInfo,
		// 		userInfo
		// 	});
		// }

		let user = await this.session('userInfo');
		if (user) {
			user = think.extend({}, user); // 复制user, 防止在view被修改，影响session
		}

		const userFlux = new Store('user', user);

		function getCreateElement(context) {

			let Provider = ContextProvider;
			Provider = providesStore(userFlux.store, Provider);
			return function createElement(Component, props) {
				return React.createElement(
					Provider, {
						userAction: userFlux.actions
					},
					React.createElement(Component, props)
				);
			}
		}

		function getRoutes(routesFile, context) {
			try {
				return think.require(routesFile)({
					userStore: userFlux.store
				});
			} catch (err) {
				think.log(err);
			}
		}

		this.assign('time', new Date().getTime());
		this.assign('user', user);
		this.assign('getCreateElement', getCreateElement);
		this.assign('getRoutes', getRoutes);
	}
	indexAction() {
		this.__call();
	}
	__call() {
		return this.display();
	}
}